﻿using Common;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using IService;
using Microsoft.Extensions.Options;
using ModelDto;

namespace AssetManegement.Filter
{
    /// <summary>
    /// 校验openid
    /// </summary>
    public class MyOpenidFilterAttribute : Attribute, IActionFilter, IFilterMetadata
    {
        private readonly IWXUserService _userService;
        private readonly IOptions<AppsettingConfig> AppConfig;
        public MyOpenidFilterAttribute(IWXUserService userService, IOptions<AppsettingConfig> options)
        {
            _userService = userService;
            AppConfig = options;
        }


        public void OnActionExecuted(ActionExecutedContext context)
        {
            //throw new NotImplementedException();
        }

        public  void OnActionExecuting(ActionExecutingContext context)
        {
            //测试openid
            string openid = "oM2yl5Jz92-h4Vx7JcwPtb_wmqWQ";
            if (AppConfig.Value.Debug != "1")
            {
                openid = "";
                openid = context.HttpContext.Request.Headers["Openid"].ToString();
            }
            if (string.IsNullOrWhiteSpace(openid))
            {
                //TOKEN 无效
                context.Result = new JsonResult(new JsonResultL().OpenIdFail("登录信息无效"));

            }
            else
            {
                var user =  _userService.GetUserByOpenid(openid);
                if (user == null)
                {
                    context.Result = new JsonResult(new JsonResultL().OpenIdFail("用户不存在"));
                }
                else
                {
                    if (user.EnableState == 2)
                    {
                        context.Result = new JsonResult(new JsonResultL().OpenIdFail("当前用户不可用"));
                    }
                }

                context.HttpContext.Request.Headers["LUser"] = Newtonsoft.Json.JsonConvert.SerializeObject(user);

            }

        }
 
    }
}
